package com.ny.controller;

import com.ny.entity.Device;
import com.ny.entity.Result;
import com.ny.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 设备
 */
@RestController
@RequestMapping("/devices")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;



    /**
     * 根据设备名称查询
     * GET http://localhost:8081/devices/name?name=传感器
     */
    @GetMapping("/name")
    public Result getDevicesByName(@RequestParam("name") String name) {
        List<Device> devices = deviceService.findDevicesByName(name);
        if (devices.isEmpty()) {
            return Result.notFound("未找到名称包含【" + name + "】的设备");
        }
        return Result.success(devices);
    }
    /**
     * 查询所有设备
     * GET http://localhost:8081/devices
     */
    @GetMapping("/getAll")
    public Result getAllDevices() {
        List<Device> devices = deviceService.findAllDevices();
        return Result.success(devices);
    }
    /**
     * 根据设备ID删除
     * DELETE http://localhost:8081/devices/1
     */
    @DeleteMapping("/{id}")
    public Result deleteDevice(@PathVariable int id) {
        // 先验证设备是否存在
        if (!deviceService.existsById(id)) {
            return Result.notFound("设备ID不存在：" + id);
        }
        // 执行删除
        int rows = deviceService.deleteDeviceById(id);
        if (rows > 0) {
            return Result.success("设备ID【" + id + "】删除成功");
        }
        return Result.error("删除失败，请重试");
    }


}
